package com.wdl.sm.webui;

import javax.servlet.Servlet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
@ConditionalOnWebApplication
@ConditionalOnClass({Servlet.class, DispatcherServlet.class, WebMvcConfigurerAdapter.class})
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@Order(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter(DispatcherServletAutoConfiguration.class)

public class WebuiConfigurerAdapter extends WebMvcConfigurerAdapter {
    private static final Logger LOG = LoggerFactory.getLogger("WebuiConfigurerAdapter");

    String myExternalFilePath = "/opt/wdl/webui/config/";
    String myStaticFilePath = "/opt/wdl/webui/static/";

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // For development purpose
        registry.addMapping("/**").allowedOrigins("http://localhost:4200");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        myExternalFilePath = "file://" + myExternalFilePath;

        LOG.info("=== Set external config path to " + myExternalFilePath + " ====");
        registry
          .addResourceHandler("/webui/**")
          .addResourceLocations(myExternalFilePath)
          .setCachePeriod(3600*24);

        registry
          .addResourceHandler("/**")
          .addResourceLocations("file://" + myStaticFilePath)
          .setCachePeriod(3600*24*30);

        super.addResourceHandlers(registry);
    }
}
